<?php
// 应用公共文件

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

if (!function_exists('success')) {
    /**
     * 返回成功的JSON响应
     * @param mixed $data 数据
     * @param string $message 消息
     * @param int $code 状态码
     * @return \think\Response
     */
    function success($data = null, $message = '操作成功', $code = 200)
    {
        $result = [
            'code' => $code,
            'message' => $message,
            'data' => $data,
            'timestamp' => time()
        ];
        return json($result);
    }
}

if (!function_exists('error')) {
    /**
     * 返回错误的JSON响应
     * @param string $message 错误消息
     * @param int $code 错误码
     * @param mixed $data 数据
     * @return \think\Response
     */
    function error($message = '操作失败', $code = 400, $data = null)
    {
        $result = [
            'code' => $code,
            'message' => $message,
            'data' => $data,
            'timestamp' => time()
        ];
        return json($result);
    }
}

if (!function_exists('generateJWT')) {
    /**
     * 生成JWT Token
     * @param array $payload 载荷数据
     * @param int $expire 过期时间（秒）
     * @return string
     */
    function generateJWT($payload, $expire = null)
    {
        $config = config('oauth.jwt');
        $expire = $expire ?: $config['expire'];

        $payload['iat'] = time();
        $payload['exp'] = time() + $expire;

        return JWT::encode($payload, $config['secret'], $config['algorithm']);
    }
}

if (!function_exists('verifyJWT')) {
    /**
     * 验证JWT Token
     * @param string $token
     * @return array|false
     */
    function verifyJWT($token)
    {
        try {
            $config = config('oauth.jwt');
            $decoded = JWT::decode($token, new Key($config['secret'], $config['algorithm']));
            return (array) $decoded;
        } catch (Exception $e) {
            return false;
        }
    }
}

if (!function_exists('generateDeviceId')) {
    /**
     * 生成设备ID
     * @param string $platform 平台
     * @param array $deviceInfo 设备信息
     * @return string
     */
    function generateDeviceId($platform, $deviceInfo = [])
    {
        $str = $platform . '_' . json_encode($deviceInfo) . '_' . time() . '_' . rand(1000, 9999);
        return md5($str);
    }
}

if (!function_exists('generateUuid')) {
    /**
     * 生成UUID
     * @return string
     */
    function generateUuid()
    {
        return sprintf(
            '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff)
        );
    }
}

if (!function_exists('encryptData')) {
    /**
     * AES加密数据
     * @param string $data 要加密的数据
     * @param string $key 密钥
     * @return string
     */
    function encryptData($data, $key)
    {
        $method = 'AES-256-CBC';
        $iv = openssl_random_pseudo_bytes(16);
        $encrypted = openssl_encrypt($data, $method, $key, 0, $iv);
        return base64_encode($iv . $encrypted);
    }
}

if (!function_exists('decryptData')) {
    /**
     * AES解密数据
     * @param string $encryptedData 加密的数据
     * @param string $key 密钥
     * @return string|false
     */
    function decryptData($encryptedData, $key)
    {
        $method = 'AES-256-CBC';
        $data = base64_decode($encryptedData);
        $iv = substr($data, 0, 16);
        $encrypted = substr($data, 16);
        return openssl_decrypt($encrypted, $method, $key, 0, $iv);
    }
}